from datetime import timedelta
from typing import Annotated

from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from passlib.context import CryptContext
from starlette import status

from src.api.controllers.responses.auth import Token
from src.config import AuthConfig, Settings
from src.core.models import dto
from src.core.utils.date import get_date_time
from src.database.services import UserService

from .stub import Stub

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/confirm")


class AuthProvider:
    def __init__(self, config: AuthConfig):
        self.config = config
        self.pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
        self.secret_key = config.secret_key
        self.algorythm = "HS256"
        self.access_token_expire = config.token_expire_minutes

    def verify_password(self, plain_password: str, hashed_password: str) -> bool:
        return self.pwd_context.verify(plain_password, hashed_password)

    def get_password_hash(self, password: str) -> str:
        return self.pwd_context.hash(password)

    def create_access_token(self, data: dict, expire_minutes: int) -> Token:
        to_encode = data.copy()
        expire = get_date_time("UTC") + timedelta(minutes=expire_minutes)
        to_encode.update({"exp": expire})
        encoded_jwt = jwt.encode(to_encode, self.secret_key, algorithm=self.algorythm)
        return Token(access_token=encoded_jwt, token_type="bearer")

    def create_user_token(self, phone_number: str) -> Token:
        return self.create_access_token(
            data={"sub": phone_number}, expire_minutes=self.access_token_expire
        )

    def decode_token(self, token: str) -> str:
        """Декодируем jwt токен"""

        credentials_exception = HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Could not validate credentials",
            headers={"WWW-Authenticate": "Bearer"},
        )
        try:
            payload = jwt.decode(token, self.secret_key, algorithms=[self.algorythm])
            subject: str = payload.get("sub")
            if subject is None:
                raise credentials_exception
        except JWTError:
            raise credentials_exception
        return subject

    async def get_current_user(
        self,
        user_service: Annotated[UserService, Depends(Stub(UserService))],
        token: str = Depends(oauth2_scheme),
    ) -> dto.UserDTO:
        phone = self.decode_token(token)

        return await user_service.get_user_by_phone_number(phone)


def get_auth_provider(
    config: Annotated[Settings, Depends(Stub(Settings))]
) -> AuthProvider:
    yield AuthProvider(config.auth)
